package cn.iocoder.yudao.module.engine.service.billing;

import cn.iocoder.yudao.module.engine.model.context.EngineSessionContext;
import cn.iocoder.yudao.module.engine.service.conn.IEngineConnectListener;
import cn.iocoder.yudao.module.resource.api.IUserTimeBalanceApi;
import cn.iocoder.yudao.module.resource.api.IUserTimeManagerApi;
import cn.iocoder.yudao.module.resource.api.model.UserTimeBalanceDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class BillingUserTimeConnectionHandler implements IEngineConnectListener {
    @Resource
    private IUserTimeManagerApi userTimeManagerApi;
    @Resource
    private IUserTimeBalanceApi userTimeBalanceApi;

    @Override
    public void onConnected(EngineSessionContext sessionCtx) {
        final UserTimeBalanceDTO balance = userTimeBalanceApi.getUserTimeBalanceByUserIdWithNewUserGive(sessionCtx.getUserId());
        final Long remainingTimeSeconds = balance != null ? balance.getRemainingTimeMs() : 0;
        if (remainingTimeSeconds > 0) {
            sessionCtx.getBillingContext().setBalanceSufficient(true);
        }
        sessionCtx.getBillingContext().startDuration();
        log.info("计费用户时长-连接创建, userId = {}, gameMatchId = {}, remainingTimeSeconds = {}}, balanceSufficient = {}",
                sessionCtx.getUserId(), sessionCtx.getGameMatchId(), remainingTimeSeconds, sessionCtx.getBillingContext().getBalanceSufficient());
    }

    @Override
    public void onDisconnected(EngineSessionContext sessionCtx) {
        final long timeMs = sessionCtx.getBillingContext().getCurrentDurationMs();
        final String gameMatchId = sessionCtx.getGameMatchId();
        final Integer roleId = sessionCtx.getRoleId();
        final String roleName = sessionCtx.getRole().getName();
        final boolean balanceSufficient = userTimeManagerApi.consumeTime(sessionCtx.getUserId(), gameMatchId, roleId, roleName, timeMs);
        log.info("计费用户时长-连接断开, userId = {}, gameMatchId = {}, balanceSufficient = {}, timeMs = {}",
                sessionCtx.getUserId(), sessionCtx.getGameMatchId(), balanceSufficient, timeMs);
    }
}
